// public/js/lobby.js

// 导出一个初始化函数
export function init(socket) {
    console.log('Lobby module initialized.');

    // DOM 元素
    const playerNameInput = document.getElementById('player-name-input');
    const roomIdInput = document.getElementById('room-id-input');
    const randomCreateBtn = document.getElementById('random-create-btn');
    const createRoomBtn = document.getElementById('create-room-btn');
    const joinRoomBtn = document.getElementById('join-room-btn');
    const randomJoinBtn = document.getElementById('random-join-btn');
    const messageArea = document.getElementById('lobby-message-area');
    let m_roomID = "";

    // 1. 创建 AbortController
    const controller = new AbortController();
    const { signal } = controller;

    // 2. 定义一个通用的事件处理函数
    function handleClick(event) {
        // event.target 就是被点击的那个按钮
        const clickedButton = event.target;
        
        let playerName = document.getElementById('player-name-input').value.trim();
        
        // 随机加入房间不需要房间ID
        if (clickedButton.id === 'random-join-btn') {
            if (!playerName) {
                playerName = generateRandomName();
                playerNameInput.value = playerName;
                updateMessage(messageArea, `已为你随机生成昵称：${playerName}`, 'inherit');
            }
            console.log('随机加入房间按钮被点击');
            socket.emit('random_join_room', { playerName });
            return;
        }
        
        // 创建房间和加入房间需要房间ID
        let roomId = document.getElementById('room-id-input').value.trim();

        if (clickedButton.id === 'random-create-btn') {
            if (!playerName) {
                playerName = generateRandomName();
                playerNameInput.value = playerName;
            }

            if (!roomId) {
                roomId = generateRandomRoomId();
                roomIdInput.value = roomId;
            }

            m_roomID = roomId;
            console.log('随机创建房间按钮被点击, 分配房间:', roomId, '昵称:', playerName);
            socket.emit('create_room', { roomId, playerName });
            return;
        }
        
        if (!playerName || !roomId) {
            updateMessage(messageArea, '昵称和房间ID不能为空！', 'red');
            return;
        }

        m_roomID = roomId;

        // 3. 根据按钮的 id 来决定要执行的操作
        if (clickedButton.id === 'create-room-btn') {
            console.log('创建房间按钮被点击');
            socket.emit('create_room', { roomId, playerName });
        } else if (clickedButton.id === 'join-room-btn') {
            console.log('加入房间按钮被点击');
            socket.emit('join_room', { roomId, playerName });
        }
    }

    // 4. 为按钮绑定事件处理函数
    randomCreateBtn.addEventListener('click', handleClick, { signal });
    createRoomBtn.addEventListener('click', handleClick, { signal });
    joinRoomBtn.addEventListener('click', handleClick, { signal });
    randomJoinBtn.addEventListener('click', handleClick, { signal });

    // 5. 将 controller 存储起来，以便在 cleanup 时使用
    window.lobbyController = controller;

    // Socket.IO 事件
    socket.on('room_creation_result',  onCreateRoom);
    socket.on('join_result', onJoinRoom);
    socket.on('random_join_result', onRandomJoinRoom);

    window.lobbySocketListeners = {
        createRoom: onCreateRoom,
        joinRoom: onJoinRoom,
        randomJoinRoom: onRandomJoinRoom
    };

    // 辅助函数
    function onJoinRoom(data) {
        console.log("join_result")
        updateMessage(data.message, data.success ? 'green' : 'red');
        if (data.success) {
                    const navigatePath = `room.html?roomId=${encodeURIComponent(m_roomID)}`;
                    console.log("m_roomID:", m_roomID);

                    const navigateEvent = new CustomEvent('navigate', {
                        detail: { path: navigatePath }
                    });

                    window.dispatchEvent(navigateEvent);
            }
    }

    function onCreateRoom(data)
    {
            console.log("room_creation_result")
            updateMessage(data.message, data.success ? 'green' : 'red');
            if (data.success) {
                // 创建一个自定义事件并触发它
                    // 事件名为 'navigate'，可以携带数据
                    // 定义导航路径
                    const navigatePath = `room.html?roomId=${encodeURIComponent(m_roomID)}`;
                    console.log("m_roomID:", m_roomID);

                    const navigateEvent = new CustomEvent('navigate', {
                        detail: { path: navigatePath }
                    });

                    window.dispatchEvent(navigateEvent);
            }
    }

    function onRandomJoinRoom(data) {
        console.log("random_join_result", data);
        updateMessage(data.message, data.success ? 'green' : 'red');
        if (data.success) {
            // 随机加入成功，导航到房间页面
            const navigatePath = `room.html?roomId=${encodeURIComponent(data.roomId)}`;
            console.log("随机加入房间ID:", data.roomId);

            const navigateEvent = new CustomEvent('navigate', {
                detail: { path: navigatePath }
            });

            window.dispatchEvent(navigateEvent);
        }
    }

    function generateRandomName() {
        const adjectives = ['快乐', '神秘', '迅捷', '勇敢', '闪亮', '智慧', '可爱', '顽皮'];
        const animals = ['狐狸', '猫咪', '海豚', '麒麟', '熊猫', '龙', '麋鹿', '鲸鱼'];
        const adjective = adjectives[Math.floor(Math.random() * adjectives.length)];
        const animal = animals[Math.floor(Math.random() * animals.length)];
        const number = Math.floor(Math.random() * 90 + 10); // 10-99
        return `${adjective}${animal}${number}`;
    }

    function generateRandomRoomId(length = 6) {
        const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        let result = '';
        for (let i = 0; i < length; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }

    function updateMessage(text, color = 'inherit') {
        if (messageArea) {
            messageArea.textContent = text;
            messageArea.style.color = color;
        }
    }
}

// 导出一个清理函数
export function cleanup(socket) {
console.log('Lobby module cleaned up.');
    // 6. 在 cleanup 时，调用 abort() 移除所有监听器
    if (window.lobbyController) {
        window.lobbyController.abort();
        console.log('Lobby event listeners have been aborted.');
        delete window.lobbyController;
    }

    if (window.lobbySocketListeners) {
        socket.off('join_result', window.lobbySocketListeners.joinRoom);
        socket.off('room_creation_result', window.lobbySocketListeners.createRoom);
        socket.off('random_join_result', window.lobbySocketListeners.randomJoinRoom);
        delete window.lobbySocketListeners;
    }
}